package org.openapi.event;

import org.openapi.consts.EventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 事件中心
 */
public class EventBus {
    private static Logger logger = LoggerFactory.getLogger(EventBus.class);
    public static ConcurrentHashMap<String, Set<EventService>> serviceMap = new ConcurrentHashMap<>();

    /**
     * 注册事件
     * @param modelCode
     * @param event
     * @param service
     */
    public static void on(String modelCode, EventType event, EventService service){
        Set<EventService> services = serviceMap.get(modelCode+":"+event.getCode());
        if(services == null){
            services = new HashSet<>();
            services.add(service);
            serviceMap.put(modelCode+":"+event, services);
        }else{
            services.add(service);
        }
        logger.info("event bus action on {} : {}", modelCode, event);
    }

    /**
     * 触发事件
     * @param modelCode
     * @param event
     * @param data
     */
    public static void call(String modelCode, EventType event, Object data){
        Set<EventService> services = serviceMap.get(modelCode+":"+event.getCode());
        if(services != null){
            services.forEach(service -> service.process(data));
        }
    }
}
